<?php
class We{

	private $appId = 'wx5126e83f09c3c777';
    private $appSecret = 'c9375bddcfca7b455211e7ed62dcf66d';

   //微信授权
   /**
     * 获取微信授权链接
     * @param string $redirect_uri 跳转地址
     * @param mixed $state 参数
     */
    public function get_authorize_url($redirect_uri = '', $state = 1)
    {
        $redirect_uri = urlencode($redirect_uri);
        return "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appId}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&state={$state}#wechat_redirect";
    }
    /**
     * 获取授权token
     * 
     * @param string $code 通过get_authorize_url获取到的code
     */
    public function get_access_token($code = '',$appId = '', $appSecret = '')
    {
        $token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appId}&secret={$this->appSecret}&code={$code}&grant_type=authorization_code";
//https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx4eab0298c0885f1f&secret=d6bb82df07eddce6206b790da30c273c&code=001e79e0f860ea5c49ef7dbcc7911e1&grant_type=authorization_code
        $token_data = $this->getJson($token_url);
        
        if($token_data)
        {
            return $token_data;
        } 
        return FALSE;
    }

    public function getToken()
    {
        $token_url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appId}&secret={$this->appSecret}";
        $token_data = $this->getJson($token_url);
        if($token_data)
        {
            return $token_data;
        }
        return FALSE;
    }

    public function getTicket($access_token,$data){

    $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$access_token;

    $result = $this->postJson($url,$data);

        return $result;


    }

    public function postJson($url,$data){
        $data_string = json_encode($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($data_string))
        );
        ob_start();
        curl_exec($ch);
        $return_content = ob_get_contents();
        ob_end_clean();

        $return_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return json_decode($return_content);
    }

    public function getUserinfo($access_token,$open_id)
    {
        if($access_token && $open_id)
        {
            $info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid={$open_id}&lang=zh_CN";
            $info_data = $this->getJson($info_url);
            return $info_data;
            if($info_data)
            {
                return json_decode($info_data, TRUE);
            }
        }

        return FALSE;
    }
    
    /**
     * 获取授权后的微信用户信息
     * 
     * @param string $access_token
     * @param string $open_id
     */
    public function get_user_info($access_token = '', $open_id = '')
    {
        if($access_token && $open_id)
        {
            $info_url = "https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$open_id}&lang=zh_CN";
            $info_data = $this->getJson($info_url);
            return $info_data;
            if($info_data)
            {
                return json_decode($info_data, TRUE);
            }
        }
        
        return FALSE;
    }
	
   /**
    * 刷新Token
    * @param string $code refresh_token refresh_token
    **/
	public function refreshToken($refresh_token) {
        if(empty($refresh_token)){
            return false;
        }
		
        $url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={$this->appId}&grant_type=refresh_token&refresh_token=" . $refresh_token;
        $Token = $this->getJson($url);
        if($Token){
			return $Token;
		}
        return false;
    }
    
    

    /**
     * 执行
     * 
     * @param string $url   要执行的地址
     */



	public function getJson($url){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($ch);
		curl_close($ch);
		return json_decode($output, true);
	}

	//end  微信授权



	/**加密解析
	 * pkcs7补码
	 *
	 * @param string $string  明文
	 * @param int $blocksize Blocksize , 以 byte 为单位
	 *
	 * @return String
	 */
	public function addPkcs7Padding($string, $blocksize = 32) {
		$len = strlen($string); //取得字符串长度
		$pad = $blocksize - ($len % $blocksize); //取得补码的长度
		$string .= str_repeat(chr($pad), $pad); //用ASCII码为补码长度的字符， 补足最后一段
		return $string;
	}

	/**
	 * 加密然后base64转码
	 *
	 * @param String 明文
	 * @param 加密的初始向量（IV的长度必须和Blocksize一样， 且加密和解密一定要用相同的IV）
	 * @param $key 密钥
	 */
	public function aes256cbcEncrypt($str, $iv, $key ) {
		$iv = substr($iv,0,32);
		$key = substr($key,0,32);
		return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $this->addPkcs7Padding($str) , MCRYPT_MODE_CBC, $iv));
	}

	/**
	 * 除去pkcs7 padding
	 *
	 * @param String 解密后的结果
	 *
	 * @return String
	 */
	public function stripPkcs7Padding($string){
		$slast = ord(substr($string, -1));
		$slastc = chr($slast);
		$pcheck = substr($string, -$slast);
		if(preg_match("/$slastc{".$slast."}/", $string)){
			$string = substr($string, 0, strlen($string)-$slast);
			return $string;
		} else {
			return false;
		}
	}

	/**
	 * 解密
	 *
	 * @param String $encryptedText 二进制的密文
	 * @param String $iv 加密时候的IV
	 * @param String $key 密钥
	 *
	 * @return String
	 */
	public function aes256cbcDecrypt($encryptedText, $iv, $key) {
		$iv = substr($iv,0,32);
		$key = substr($key,0,32);
		$encryptedText =base64_decode($encryptedText);
		return $this->stripPkcs7Padding(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $encryptedText, MCRYPT_MODE_CBC, $iv));
	}

	//end  加密解析



}